<template>
  <div>
    <el-button type="primary" @click="addClassificationVisible = true">添加分类</el-button>
    <!--    表格-->
    <tree-table :columns="columns"
                :data="cateList"
                :expand-type="false"
                :selection-type="false"
                :show-row-hover="false"
                border
                index-text="#"
                show-index>
      <!-- 是否有效区域， 设置对应的模板列： slot="isok"(与columns中设置的template一致) -->
      <template slot="isok" slot-scope="scope">
        <i v-if="scope.row.cat_deleted === false" class="el-icon-success" style="color:lightgreen"></i>
        <i v-else class="el-icon-error" style="color:red"></i>
      </template>

      <!-- 排序 -->
      <template slot="order" slot-scope="scope">
        <el-tag v-if="scope.row.cat_level===0" size="mini">一级</el-tag>
        <el-tag v-else-if="scope.row.cat_level===1" size="mini" type="success">二级</el-tag>
        <el-tag v-else size="mini" type="warning">三级</el-tag>
      </template>

      <!-- 操作 -->
      <template slot="opt" slot-scope="scope">
        <el-button icon="el-icon-edit" size="mini" type="primary" @click="putListItem(scope.row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="mini" type="danger" @click="deleteListItem(scope.row)">删除</el-button>
      </template>
    </tree-table>

    <!--    分页-->
    <el-pagination
      :current-page="queryInfo.pagenum"
      :page-size="queryInfo.pagesize"
      :page-sizes="[5, 10, 15, 20]"
      :total="total"
      background
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>

    <!--    添加分类-->
    <el-dialog :visible.sync="addClassificationVisible" title="添加分类">
      <el-form ref="addClassification" :model="formData" :rules="rules">
        <el-form-item label="分类名称：" label-width="100px" prop="cat_name">
          <el-input v-model.trim="formData.cat_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：" label-width="100px">
          <el-cascader
            :options="cateList"
            :props="{
              checkStrictly: true,
              label:'cat_name',
              value:'cat_id',
              expandTrigger:'hover'
            }"
            clearable
            style="width: 100%;"
            @change="onChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addClassificationVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClassification">确 定</el-button>
      </div>
    </el-dialog>
    <!--      /添加分类-->

    <!--    修改分类-->
    <el-dialog :visible.sync="putClassificationVisible" title="修改分类">
      <el-form ref="putClassification" :model="cat_name" :rules="rulesPut">
        <el-form-item label="分类名称：" label-width="100px" prop="name">
          <el-input v-model.trim="cat_name.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="putClassificationVisible = false">取 消</el-button>
        <el-button type="primary" @click="putClassification">确 定</el-button>
      </div>
    </el-dialog>
    <!--      /修改分类-->
  </div>
</template>

<script>
import { deleteCategories, getCategories, postCategories, putCategories } from '@/api/commodity'

export default {
  name: 'categories',
  data () {
    return {
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        // type:'template'(将该列设置为模板列)，template:'isok'(设置该列模板的名称为isok)
        {
          label: '是否有效',
          prop: '',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          prop: '',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          prop: '',
          type: 'template',
          template: 'opt'
        }
      ],
      // 商品分类数据列表
      cateList: [],
      // 查询分类数据的条件
      queryInfo: {
        type: '',
        pagenum: 1,
        pagesize: 10
      },
      // 保存总数据条数
      total: 0,
      addClassificationVisible: false,
      putClassificationVisible: false,
      formData: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      rules: {
        cat_name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }
        ]
      },
      rulesPut: {
        name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }
        ]
      },
      id: '',
      cat_name: {
        name: ''
      }
    }
  },
  methods: {
    // 修改分类
    putListItem (item) {
      // console.log(item)
      this.id = item.cat_id
      this.cat_name.name = item.cat_name
      this.putClassificationVisible = true
    },
    // 确认修改请求
    async putClassification () {
      try {
        await this.$refs.putClassification.validate()
        try {
          const res = await putCategories(this.id, this.cat_name.name)
          if (res.meta.status === 200) {
            this.$message.success('分类修改成功')
            this.putClassificationVisible = false
            // 刷新页面数据
            await this.getCategoriesList()
          } else {
            this.$message.error(res.meta.msg)
          }
        } catch (e) {
          this.$message.error('分类修改失败')
        }
      } catch {
        this.$message.error('请输入分类名')
      }
    },
    // 删除分类
    deleteListItem (item) {
      // console.log(item)
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log(str.id)
        deleteCategories(item.cat_id).then(res => {
          if (res.meta.status === 200) {
            // 刷新页面数据
            this.getCategoriesList()
            this.$message({
              message: res.meta.msg,
              type: 'success'
            })
          } else {
            this.$message.error(res.meta.msg)
          }
        }).catch(() => {
          this.$message.error('删除失败')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 添加分类按钮
    async addClassification () {
      try {
        await this.$refs.addClassification.validate()
        try {
          const res = await postCategories(this.formData)
          if (res.meta.status === 201) {
            this.$message.success('分类添加成功')
            this.addClassificationVisible = false
            // 刷新页面数据
            await this.getCategoriesList()
          } else {
            this.$message.error(res.meta.msg)
          }
        } catch (e) {
          this.$message.error('分类添加失败')
        }
      } catch {
        this.$message.error('请输入分类名')
      }
    },
    // 选择分级
    onChange (value) {
      if (value.length === 1) {
        this.formData.cat_pid = 0
        this.formData.cat_level = 0
      } else if (value.length === 3) {
        this.formData.cat_pid = value.at(-2)
        this.formData.cat_level = value.length - 1
      } else {
        this.formData.cat_pid = value.at(-1)
        this.formData.cat_level = value.length
      }
    },
    // 请求分页数据
    async getCategoriesList () {
      const res = await getCategories(this.queryInfo)
      // console.log(res.data)
      this.total = res.data.total
      this.cateList = res.data.result
    },
    // 一页有多少项
    handleSizeChange (value) {
      console.log(value)
      this.queryInfo.pagesize = value
      this.getCategoriesList()
    },
    // 去往第几页
    handleCurrentChange (value) {
      // 发起请求前, 无论之前的请求在什么阶段 都将其终止
      // console.log(this.$httpRequestList)
      if (this.$httpRequestList.length > 0) {
        this.$httpRequestList.forEach(item => {
          item()
          this.$httpRequestList.shift()
        })
      }
      console.log(value)
      this.queryInfo.pagenum = value
      this.getCategoriesList()
    }
  },
  created () {
    this.getCategoriesList()
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-table__expand-icon {
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);

}

/deep/ .cell {
  position: relative;

  .el-table__expand-icon {
    position: absolute;
    top: 1px;
    left: 22px;
    z-index: 999;
  }

}

/*2.展开按钮未点击的样式是加号带边框*/
/deep/ .el-table__expand-icon .el-icon-arrow-right:before {
  content: "\e6d9";
  border: 1px solid #ccc;
  padding: 1px;
}

/*2.按钮已点击展开之后的样式是减号带边框*/
/deep/ .el-table__expand-icon--expanded .el-icon-arrow-right:before {
  content: "\e6d8";
}

</style>
